<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android,动态加载," />





  <link rel="alternate" href="/atom.xml" title="GrantonZhuang's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="动态加载 so 库关于动态加载 so 库，这篇文章 有很详细的讲解，这里只贴出部分学习笔记。">
<meta property="og:type" content="article">
<meta property="og:title" content="Android 动态加载 so 库学习笔记">
<meta property="og:url" content="https://grantonzhuang.github.io/2016/06/05/Android 动态加载 so 库学习笔记/index.html">
<meta property="og:site_name" content="GrantonZhuang's Blog">
<meta property="og:description" content="动态加载 so 库关于动态加载 so 库，这篇文章 有很详细的讲解，这里只贴出部分学习笔记。">
<meta property="og:updated_time" content="2016-07-29T13:56:02.584Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android 动态加载 so 库学习笔记">
<meta name="twitter:description" content="动态加载 so 库关于动态加载 so 库，这篇文章 有很详细的讲解，这里只贴出部分学习笔记。">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://grantonzhuang.github.io/2016/06/05/Android 动态加载 so 库学习笔记/"/>

  <title> Android 动态加载 so 库学习笔记 | GrantonZhuang's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">GrantonZhuang's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android 动态加载 so 库学习笔记
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-06-05T13:09:28+08:00" content="2016-06-05">
              2016-06-05
            </time>
          </span>

          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="动态加载-so-库"><a href="#动态加载-so-库" class="headerlink" title="动态加载 so 库"></a>动态加载 so 库</h2><p>关于动态加载 so 库，<a href="https://segmentfault.com/a/1190000004062899" target="_blank" rel="external">这篇文章</a> 有很详细的讲解，这里只贴出部分学习笔记。</p>
<a id="more"></a>
<p>System 类有两个加载 so 库的方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"> * See &#123;<span class="doctag">@link</span> Runtime#load&#125;.</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">load</span><span class="params">(String pathName)</span> </span>&#123;</div><div class="line">    Runtime.getRuntime().load(pathName, VMStack.getCallingClassLoader());</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">/**</span></div><div class="line"> * See &#123;<span class="doctag">@link</span> Runtime#loadLibrary&#125;.</div><div class="line"> */</div><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">loadLibrary</span><span class="params">(String libName)</span> </span>&#123;</div><div class="line">    Runtime.getRuntime().loadLibrary(libName, VMStack.getCallingClassLoader());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ul>
<li><code>load(String pathName)</code> 从 so 库的路径加载 so 库</li>
<li><code>loadLibrary(String libName)</code> 根据 so 库的名字加载 so 库（系统在安装应用的时候，扫描包内是否存在 so 库，并且复制到对应的标准的内部存储路径中，所以可以根据 so 库的名字加载）</li>
</ul>
<p>所以一个可行的动态加载 so 库的思路是，从网上下载需要的 so 库，复制到内部存储（外部存储中的文件没有可执行的权限），再使用 <code>loadLibrary(String libName)</code> 方法加载 so 库。</p>
<h2 id="为使用-Realm-的应用瘦身"><a href="#为使用-Realm-的应用瘦身" class="headerlink" title="为使用 Realm 的应用瘦身"></a>为使用 Realm 的应用瘦身</h2><p>Realm 是一个工作在 navtive 层的帮助开发者对数据进行本地存储的框架。</p>
<p>虽然工作在 native 层给程序运行的效率带来了很大的提高，但因为需要支持不同的 CPU 架构，所以引用了 Realm 的应用的包体积，也不可避免的增大了许多。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">➜  lib  <span class="built_in">pwd</span></div><div class="line">/home/grant/Desktop/app-debug/lib</div><div class="line">➜  lib  tree</div><div class="line">.</div><div class="line">├── arm64-v8a</div><div class="line">│   └── librealm-jni.so</div><div class="line">├── armeabi</div><div class="line">│   └── librealm-jni.so</div><div class="line">├── armeabi-v7a</div><div class="line">│   └── librealm-jni.so</div><div class="line">├── mips</div><div class="line">│   └── librealm-jni.so</div><div class="line">├── x86</div><div class="line">│   └── librealm-jni.so</div><div class="line">└── x86_64</div><div class="line">    └── librealm-jni.so</div><div class="line"></div><div class="line">6 directories, 6 files</div></pre></td></tr></table></figure>
<p>我们可以看到，解压安装包以后，lib 目录下存在六份 so 文件，但是</p>
<blockquote>
<p>Android 包管理器安装 APK 时，会自动选择 APK 包中为对应系统 ABI 预编译好的 .so 文件，如果在对应的 lib/ABI 目录中存在 .so 文件的话。</p>
</blockquote>
<p>所以，实际上安装包上的六个 so 库，对于用户的手机来说，只有一个是会被安装，并且起作用的。</p>
<p>那么，其他的五个 so 库实际上是多余的，如果能够从安装包中去掉多余的五个 so 库，就可以达到为 APK 瘦身的目的。</p>
<p>我们如何得知系统支持何种 ABI 架构？使用 Android 自带的 API 即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@TargetApi</span>(Build.VERSION_CODES.LOLLIPOP)</div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">getSupportABIS</span><span class="params">()</span> </span>&#123;</div><div class="line">    String[] supportedAbis = Build.SUPPORTED_ABIS;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我们再来看 Realm 是如何加载 so 库的。</p>
<p>查看 Realm 的源码，<code>io.realm.internal.Realm$loadLibrary</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">loadLibrary</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">if</span> (libraryIsLoaded) &#123;</div><div class="line">        <span class="comment">// 如果库已经加载过了，则返回，避免多次加载</span></div><div class="line">        <span class="keyword">return</span>;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">if</span> (osIsWindows()) &#123;</div><div class="line">        loadLibraryWindows();</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">else</span> &#123;</div><div class="line">        String jnilib;</div><div class="line">        String debug = System.getenv(<span class="string">"REALM_JAVA_DEBUG"</span>);</div><div class="line">        <span class="keyword">if</span> (debug == <span class="keyword">null</span> || debug.isEmpty()) &#123;</div><div class="line">            jnilib = <span class="string">"realm-jni"</span>;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">else</span> &#123;</div><div class="line">            jnilib = <span class="string">"realm-jni-dbg"</span>;</div><div class="line">        &#125;</div><div class="line">        System.loadLibrary(jnilib);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">// 在这里将标识位更改为 true</span></div><div class="line">    libraryIsLoaded = <span class="keyword">true</span>;</div><div class="line"></div><div class="line">    Version.coreLibVersionCompatible(<span class="keyword">true</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我们可以在自定义 Application 中先于 Realm 框架</p>
<ul>
<li>获取系统支持的 ABI 架构</li>
<li>下载我们需要的 so 库，复制到内部存储，使用动态加载的办法加载 so 库中</li>
<li>使用反射修改 <code>libraryIsLoaded</code> 变量的值为 true，避免二次加载</li>
<li>手动调用 <code>Version.coreLibVersionCompatible(true);</code> 方法</li>
</ul>
<p>这样子，在编译过后的 APK 中，我们可以将对应的 so 库都删除掉，在用户首次使用应用的时候，使用动态加载的方法加载 so 库，从而达到为应用瘦身的目的。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag">#Android</a>
          
            <a href="/tags/动态加载/" rel="tag">#动态加载</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/05/28/Android-动态加载进阶-代理Activity/" rel="next" title="Android-动态加载进阶-代理Activity和提供资源文件">
                <i class="fa fa-chevron-left"></i> Android-动态加载进阶-代理Activity和提供资源文件
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/06/10/AndroidIPC学习笔记1/" rel="prev" title="Android IPC 学习笔记 1 使用 AIDL 进行进程间通信入门">
                Android IPC 学习笔记 1 使用 AIDL 进行进程间通信入门 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://ww1.sinaimg.cn/mw690/6e8939a6gw1f3g1u1mc6lj20hs0hsmxf.jpg"
               alt="Granton Zhuang" />
          <p class="site-author-name" itemprop="name">Granton Zhuang</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives/index.html">
              <span class="site-state-item-count">26</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#动态加载-so-库"><span class="nav-number">1.</span> <span class="nav-text">动态加载 so 库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#为使用-Realm-的应用瘦身"><span class="nav-number">2.</span> <span class="nav-text">为使用 Realm 的应用瘦身</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Granton Zhuang</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  

  

  

</body>
</html>
